var map = {};
var chargingStationStatistics = undefined;
var chargingStationData = [];
var chargingDegreeTotal = undefined;
var chargingDegreeTotalLast = undefined;
var chargingDegreeTotalW = undefined;
var carbonReductionTotal = undefined;
var carbonReductionTotalLast = undefined;
var carbonReductionTotalW = undefined;
var chargingStationCount = undefined;
var chargingStationCountLast = undefined;
var equipmentDCCount = undefined;
var equipmentDCCountLast = undefined;
var chargingCountDay = undefined;
var chargingCountDayLast = undefined;
var chargingDegreeDay = undefined;
var chargingDegreeDayLast = undefined;
var chargingDegreeMonth = undefined;
var chargingDegreeMonthLast = undefined;
var countUp = undefined;
var planningMarkers = [];
var bulidingMarkers = [];
var bulitMarkers = [];
var planningClustererOptions = undefined;
var bulidingClustererOptions = undefined;
var bulitClustererOptions = undefined;
var planningCluster = undefined;
var bulidingCluster = undefined;
var bulitCluster = undefined;
var chargingStationBulitData = [];

var chargingStationIndex = undefined;

$(document).ready(function() {
   $('title', parent.document).html($('title').text());
   setBaseUrl();
   map = setMap('', '', 11, 'fresh');
   AMap.event.addListener(map, 'click', hideChargingStationDetail);
   $ajaxList('realTimeChargingStationStatistics', getRealTimeChargingStationStatistics);
});

function hideChargingStationDetail() {
	$('#mapChargingStationDetail').hide();
}

function getRealTimeChargingStationStatistics(data) {
	chargingStationStatistics = data && data.chargingStationStatistics || {};
	//总充电量
	chargingDegreeTotal = floor(chargingStationStatistics.chargingDegreeTotal || 0, 0);
	chargingDegreeTotalLast = getCountUp("chargingDegreeTotal", (chargingDegreeTotalLast || 0), chargingDegreeTotal, 0);
	chargingDegreeTotalW = getCountUp("chargingDegreeTotalW", (chargingDegreeTotalW || 0), chargingDegreeTotal/10000);
	//总碳减量
	carbonReductionTotal = ((2.63 + 0.878) * (chargingDegreeTotal * 2.5 /10) - chargingDegreeTotal * 0.5) / 1000;
	carbonReductionTotalLast = getCountUp("carbonReductionTotal", (carbonReductionTotalLast || 0), carbonReductionTotal, 0);
	carbonReductionTotalW = getCountUp("carbonReductionTotalW", (carbonReductionTotalW || 0), carbonReductionTotal/1000, 0);
	//总充电站
	chargingStationCountLast = getCountUp("chargingStationCount", (chargingStationCountLast || 0), chargingStationStatistics.chargingStationCount || 0, 0);
	//总直流充电桩
	equipmentDCCountLast = getCountUp("equipmentDCCount", (equipmentDCCountLast || 0), chargingStationStatistics.equipmentDCCount || 0, 0);
	//日充电次数
	chargingCountDayLast = getCountUp("chargingCountDay", (chargingCountDayLast || 0), chargingStationStatistics.chargingCountDay || 0, 0);
	//日充电度数
	chargingDegreeDayLast = getCountUp("chargingDegreeDay", (chargingDegreeDayLast || 0), floor(chargingStationStatistics.chargingDegreeDay || 0, 0), 0);
	//月充电度数
	chargingDegreeMonthLast = getCountUp("chargingDegreeMonth", (chargingDegreeMonthLast || 0), floor(chargingStationStatistics.chargingDegreeMonth || 0, 0), 0);	
    //地图充电站信息
	if (data.chargingStationList) {
		chargingStationData = data && data.chargingStationList || [];
		addMarker(chargingStationData);
	}
	//刷新统计信息
    setTimeout(freshStatistics, 3000);
}

function freshStatistics() {
	$ajaxList('realTimeChargingStationStatistics', getRealTimeChargingStationStatistics, { type: "statistics", 
		chargingStationID: (chargingStationBulitData && chargingStationBulitData.length > 0 ? getCheckDataList(chargingStationBulitData, "chargingStationID") || " " : undefined)});
}

function getCountUp(ID, lastData, thisData, decimals){
	if (thisData != lastData) {
		countUp = new CountUp(ID, lastData, thisData, decimals, 2, {useEasing: true, useGrouping: true, separator: ',', decimal: '.', prefix: '', suffix: ''});
		countUp.start();
	    countUp = null;
	}
	return thisData;
}

function addMarker(data) {
	var length = data.length;
	for (var i=0; i<length; i++) {
		if (data[i].longitude && data[i].latitude) {
			var marker = new AMap.Marker({
				// 图标样式
				// icon: "images/companyPosition.jpg",
				// 地图
		        map: map,
		        //content:'<div class="marker" >' + (i + 1) + '</div>',
		        content: setMarkerContent(data[i], i),
		        // 位置
		        position: [data[i].longitude, data[i].latitude],
		        // 动画效果：AMAP_ANIMATION_NONE(无动画)/AMAP_ANIMATION_DROP(掉落)/AMAP_ANIMATION_BOUNCE(弹跳)
		        animation: "AMAP_ANIMATION_DROP",
		        bubble: true,
		        topWhenClick: true
		    });
			if (data[i].bulidStatus == '1') {
				planningMarkers.push(marker);
			} else if (data[i].bulidStatus == '2') {
				bulidingMarkers.push(marker);
			} else if (data[i].bulidStatus == '3') {
				bulitMarkers.push(marker);
			}
			marker = null;
		}
	}
	$("#planningStatus").html("规划中(" + planningMarkers.length + ") ");
	$("#bulidingStatus").html("建设中(" + bulidingMarkers.length + ") ");
	$("#bulitStatus").html("已投运(" + bulitMarkers.length + ") ");
	addCluster();
}

function addCluster() {
	// 自动缩放
	//	map.setFitView();
	if (!planningClustererOptions) {
		planningClustererOptions = {
			styles: [{url: "static/images/polymerizationBg.png",  size: new AMap.Size(40, 40)},
			         {url: "static/images/polymerizationBg.png", size: new AMap.Size(40, 40),},
			         {url: "static/images/polymerizationBg.png", size: new AMap.Size(40, 40),}],
			gridSize: 100,
			averageCenter: true, //聚合点的图标位置是否是所有聚合内点的中心点
		}
	}
	if (!bulidingClustererOptions) {
		bulidingClustererOptions = {
			styles: [{url: "static/images/polymerizationBg.png", size: new AMap.Size(40, 40)},
			         {url: "static/images/polymerizationBg.png", size: new AMap.Size(40, 40)},
			         {url: "static/images/polymerizationBg.png", size: new AMap.Size(40, 40)}],
			gridSize: 100,
			averageCenter: true, //聚合点的图标位置是否是所有聚合内点的中心点
		}
	}
	if (!bulitClustererOptions) {
		bulitClustererOptions = {
			styles: [{url: "static/images/polymerizationBg.png", size: new AMap.Size(40, 40)},
			         {url: "static/images/polymerizationBg.png", size: new AMap.Size(40, 40)},
			         {url: "static/images/polymerizationBg.png", size: new AMap.Size(40, 40)}
			],
			gridSize: 100,
			averageCenter: true, //聚合点的图标位置是否是所有聚合内点的中心点
		}
	}
	planningCluster = new AMap.MarkerClusterer(map, planningMarkers, planningClustererOptions);
	bulidingCluster = new AMap.MarkerClusterer(map, bulidingMarkers, bulidingClustererOptions);
	bulitCluster = new AMap.MarkerClusterer(map, bulitMarkers, bulitClustererOptions);
	if (!$("#cluster").is(':checked')) {
		map.remove(planningCluster);
		map.remove(bulidingCluster);
		map.remove(bulitCluster);
		if ($("#bulidStatus1").is(':checked')) {
			map.add(planningMarkers);
		}
		if ($("#bulidStatus2").is(':checked')) {
			map.add(bulidingMarkers);
		}
		if ($("#bulidStatus3").is(':checked')) {
			map.add(bulitMarkers);
		}
	} else {
		if (!$("#bulidStatus1").is(':checked')) {
			map.remove(planningCluster);
		}
		if (!$("#bulidStatus2").is(':checked')) {
			map.remove(bulidingCluster);
		}
		if (!$("#bulidStatus3").is(':checked')) {
			map.remove(bulitCluster);
		}
	}
}

function setMarkerContent(data, index) {
	var content = [];
	var equipmentCount = parseInt(data.bgEquipmentCount || 0, 10) + parseInt((data.smEquipmentCount || 0), 10);
	var chargingStationName = data.chargingStationName.replace(/[^0-9]/ig, "");
	if (chargingStationName.length == 0) {
		if (data.chargingStationName.substring(0, 3) == "北京市") {
			chargingStationName = data.chargingStationName.substring(3, 4);
		} else if (data.chargingStationName.substring(0, 2) == "北京") {
			chargingStationName = data.chargingStationName.substring(2, 3);
		} else {
			chargingStationName = data.chargingStationName.substring(0, 1);
		}
	}
	if (chargingStationName.length > 3) {
		chargingStationName = data.chargingStationName.substring(0, 1);
	}
	content.push('<div id="markerContent' + index + '" class="markerContent" title="'+ data.chargingStationName +'" onclick="showMapChargingStationDetail(' + index + ','+ equipmentCount +')">');
	content.push('<div class="markerSm">' + chargingStationName + '</div>');
	content.push('</div></div>');
	return content.join('');
}

function changeBulidSelect(value){
	if (value) {
		$(".bulidSelect").css({right : '295px'});
	} else {
		$(".bulidSelect").css({right : '165px'});
	}
}

function showStatisticsSelectImage(imageOne, imageTwo){
	$('#' + imageOne).show();
	$('#' + imageTwo).hide();
}
function changeStatisticsSelect(){
	if (!$("#statisticsSelect").html()) {
		$("#statisticsSelect").html('');
		var length = chargingStationData.length;
		if (length > 0) {
			$("#statisticsSelect").append('<label class="cursor"><input type="checkbox" id="chk" checked onclick="checkAll(\'chk\')">&nbsp;全部</label><br>');
			for (var i = 0; i < length; i++) {
				if (chargingStationData[i].bulidStatus == '3') {
					chargingStationBulitData.push(chargingStationData[i]);
					$("#statisticsSelect").append('<label class="cursor"><input  type="checkbox" checked name="chk" id="'+ chargingStationData[i].chargingStationID +'" >&nbsp;'+ chargingStationData[i].chargingStationName + '</label><br>');
				}
			}
		}
	}
	$("#statisticsSelect").show();
}
function hideStatisticsSelect(){
	$("#statisticsSelect").hide();
}

function chargingStationRealTimeDetail(index) {
	window.parent.skipMenu('chargingStation/chargingStationRealTimeDetail', 'drownDown1', '', 'chargingStationPage', 'chargingStationStatus');
	$("#parentSkipMenu", parent.document).val("homePage");
	$("#detailID", parent.document).val(chargingStationData[index].chargingStationID);
}
function chargingStationDetail(index){
	window.parent.detalisDrop('chargingStation/chargingStationDetail', "drownDown1", "" ,"chargingStationPage" ,"chargingStation");
	$("#parentSkipMenu", parent.document).val("chargingStationPage");
	$("#detailID", parent.document).val(chargingStationData[index].chargingStationID);
}
function getBulidStatus(data) {
	var bulidStatusStatus= [];
	var bulidStatusMsg = "";
	var bulidStatusColor = "black";
	if (data.bulidStatus == '1') {
		// 规划中
		bulidStatusMsg = "(规划中)";
		bulidStatusColor = "#929292";
	} else if (data.bulidStatus == '2') {
		// 建设中
		bulidStatusMsg = "(建设中)";
		bulidStatusColor = "#e4ae1e";
	} else if (data.bulidStatus == '3') {
		// 已投运
		bulidStatusMsg = "(已投运)";
		bulidStatusColor = "#1abc9c";
	}
	bulidStatusStatus.push(bulidStatusMsg);
	bulidStatusStatus.push(bulidStatusColor);
	return bulidStatusStatus;
}
function showMapChargingStationDetail(index, equipmentCount) {
	showLoading();
	var mapChargingStationDetail = $("#mapChargingStationDetail");
	mapChargingStationDetail.empty();
	var statusImage = '<img src="static/images/redNoLine.png" style="margin-bottom:5px;"/>';
	var equipmentACDiv = "";
	var equipmentACImage = "";
	if (chargingStationData[index] && chargingStationData[index].equipmentCountAC > 0) {
		equipmentACDiv = 
			'<div class="col-sm-4 allColPadding">' + 
			'<div class="col-sm-12 marginBottom2Ten FontColorGreen"><span id="onlineDC" style="font-size:32px;">0</span>个 / <span style="font-size:32px;">' + 
			(chargingStationData[index].equipmentCountAC || (equipmentCount - (chargingStationData[index].equipmentCountDC || 0)) || 0) + '</span>个</div>' +
			'<div class="col-sm-12">交流: 充电中/总数</div></div>';
		equipmentACImage = '<span style="float: right;"><img src="static/images/equipmentAC.png" style="margin-top:5px;margin-right: 30px;"/></span>';
	}
	mapChargingStationDetail.append( '<div id="markerLg' + index + '" class="markerLg" style="border-top:2px solid '+ getBulidStatus(chargingStationData[index])[1] +'">' +
		'<div class="markerLgTitle" style="background-color:rgba(255, 255, 255, 0.95);padding-left: 86px;color:black;font-size: 22px;"><strong id="chargingStationName" style="color:'+ getBulidStatus(chargingStationData[index])[1] +'">' +
		(index + 1) + " " + (chargingStationData[index].chargingStationName || '充电站') + getBulidStatus(chargingStationData[index])[0] +
		'</strong><span id="onlineStatus">'+ statusImage +'</span>' + equipmentACImage +
		'<span style="float: right;"><img src="static/images/equipmentDC.png" id="equipmentDCimg"/></span>' +
		'</div>' +
		'<span style="position: absolute;font-size: 12px;color: #999;z-index: 10;margin-top: -10px; margin-left: 115px;">站当前版本号:<span>-</span></span>' +
		'<div class="col-sm-12 markerLgContent">' +
		'<div class="col-sm-5" style="min-height: 100px;margin-top:30px;border-right:1px solid rgba(0, 10, 18, 0.13);">' +
		'<div class="col-sm-4 allColPadding">' + 
		'<div class="col-sm-12 marginBottom2Ten FontColorGreen"><span id="chargingKWHDaySpan" style="font-size:32px;">0</span> 度</div>' +
		'<div class="col-sm-12">今日充电度数</div></div>' +
		'<div class="col-sm-4 allColPadding">' +
		'<div class="col-sm-12 marginBottom2Ten FontColorGreen"><span id="chargingCountDays" style="font-size:32px;">0</span> 次</div>' +
		'<div class="col-sm-12">今日充电次数</div></div>' +
		'<div class="col-sm-4 allColPadding">' + 
		'<div class="col-sm-12 marginBottom2Ten FontColorGreen"><span id="onlineDC" style="font-size:32px;">0</span>个 / <span style="font-size:32px;">' + 
		(chargingStationData[index].equipmentCountDC || (equipmentCount - (chargingStationData[index].equipmentCountAC || 0)) || 0) + '</span>个</div>' +
		'<div class="col-sm-12">直流: 充电中/总数</div></div>' +
		equipmentACDiv + 
		'</div>' +
		'<div class="col-sm-5" style="min-height: 100px;margin-top:30px;">' +
		'<div class="col-sm-3 allColPadding">' + 
		'<div class="col-sm-12 marginBottom2Ten lineHeight45" id="equipmentCount' + index + '"><span  style="font-size:26px;">' + (equipmentCount || 0) + '</span> 个</div>' +
		'<span class="col-sm-12">充电桩总数</span></div>' +
		'<div class="col-sm-3 allColPadding">' +
		'<div class="col-sm-12 marginBottom2Ten lineHeight45"><span id="carCount" style="font-size:26px;">0</span> 辆</div>' +
		'<span class="col-sm-12">本站运营车辆 </span></div>' +
		'<div class="col-sm-3 allColPadding">'+
		'<div class="col-sm-12 marginBottom2Ten lineHeight45" style="font-size:26px;">-</div>' +
		'<span class="col-sm-12">故障桩</span></div>' +
		'<div class="col-sm-3 allColPadding">' +
		'<div class="col-sm-12 marginBottom2Ten lineHeight45"><a id="countAbnormal" class="details" style="color:#00a3ff;font-size:26px;" onclick="abnormalChargingRecord(\''+ chargingStationData[index].chargingStationID +'\')">0</a> 条</div>' +
		'<span class="col-sm-12">异常充电记录 </span></div>' +
		'</div>' +
		'<div class="col-sm-2" style="min-height: 100px;margin-top:30px;padding-top:20px;">' +
		'<div class="col-sm-12 allColPadding marginBottom2Ten"><a onclick="chargingStationDetail' + '(' + index + ')' + '" style="font-size: 16px;color:#00a3ff;" class="details">信息档案 ></a></div>'+ 
		'<div class="col-sm-12 allColPadding"><a onclick="chargingStationRealTimeDetail' + '(' + index + ')' + '" style="font-size: 16px;color:#00a3ff;" class="details">实时状态 ></a></div>'+ 
		'</div>' +
		'</div></div></div>');
	$("#mapChargingStationDetail").show();
	$ajaxList('getChargingStationMapStatus', getChargingStationMapStatus, {chargingStationID: chargingStationData[index].chargingStationID});
	chargingStationIndex = index;
}
function getChargingStationMapStatus(data) {
	var singleStationData = data && data.singleStationList || [];
	$("#carCount").html((singleStationData[0].carCount || 0));
	$("#countAbnormal").html((singleStationData[0].countAbnormal || 0));
	$("#chargingKWHDaySpan").html(ThousandsSeparator(singleStationData[0].chargingKWHDay || 0));
	$("#chargingCountDays").html(singleStationData[0].chargingCountDay || 0);
	if (data) {
		if (data.onlineStatus == "在线" ){
			$('#onlineStatus').html('<img src="static/images/greenLine.png" style="margin-bottom:5px;"/>');
		} else {
			$('#onlineStatus').html('<img src="static/images/redNoLine.png" style="margin-bottom:5px;"/>');
		}
		$("#onlineDC").html(data.onLineCount || 0);
	}
	setTimeout(hideLoading, 500);
}
function showMarkerSm(index) {
	$('#mapChargingStationDetail').hide();
}

function getMarkerImage(data) {
	var imageUrl = "getChargingStationImage";
	var imageNameList = data.chargingStationImageName || [];
	var length = imageNameList.length;
	var content = [];
	data.initialPreview = [];
	data.initialPreviewConfig = [];
	content.push('<div class="item active">');
	if (length > 0) {
		content.push('<img src="' + imageUrl + '?subfolder=' + data.chargingStationID + '&&fileName=' + imageNameList[0] + '" style="width:100%;"' + '<br>');
		data.initialPreview.push('<img src="' + imageUrl + '?subfolder=' + data.chargingStationID + '&&fileName=' + imageNameList[0] + '" style="width:300px;height:160px;" />');
		data.initialPreviewConfig.push({url: "deleteChargingStationImage", extra: {fileName: imageNameList[0], subfolder: data.chargingStationID}});
	} else {
		content.push('<img src="static/images/chargingStationBus.png" style="width:100%;"' + '<br>');
	}
	content.push('</div>');
	for (var i=1; i<length; i++) {
		content.push('<div class="item">');
		content.push('<img src="' + imageUrl + '?subfolder=' + data.chargingStationID + '&&fileName=' + imageNameList[i] + '" style="width:100%;"' + '<br>');
		content.push('</div>');
		data.initialPreview.push('<img src="' + imageUrl + '?subfolder=' + data.chargingStationID + '&&fileName=' + imageNameList[i] + '" style="width:300px;height:160px;" />');
		data.initialPreviewConfig.push({url: "deleteChargingStationImage", extra: {fileName: imageNameList[i], subfolder: data.chargingStationID}});
	}
	return content.join('');
}

function chargingStationPage(bulitStatus){
	window.parent.passVal(bulitStatus, "passValue", 'chargingStation/chargingStation', 'drownDown1', '', 'chargingStationPage', 'chargingStation');
}
function abnormalChargingRecord(value){
	window.parent.passVal(value, "passValue", "chargingEquipment/abnormalRecord", "drownDown4", "", "chargingRecordPage", "abnormalRecord");
}
function clickCheckbox(item) {
	if (item.value == '0') {
		if (item.checked) {
			$("#bulidStatus :checkbox").each(function(i, item) {
				if (item.checked) {
					if (item.value == '1') {
						map.add(planningCluster);
					} else if (item.value == '2') {
						map.add(bulidingCluster);
					} else if (item.value == '3') {
						map.add(bulitCluster);
					}
				}
			})
		} else {
			map.remove(planningCluster);
			map.remove(bulidingCluster);
			map.remove(bulitCluster);
			$("#bulidStatus :checkbox").each(function(i, item) {
				if (item.checked) {
					if (item.value == '1') {
						map.add(planningMarkers);
					} else if (item.value == '2') {
						map.add(bulidingMarkers);
					} else if (item.value == '3') {
						map.add(bulitMarkers);
					}
				}
			})
		}
	} else if (item.value == '1') {
		if (item.checked) {
			if ($("#cluster").is(':checked')) {
				map.add(planningCluster);
			} else {
				map.add(planningMarkers);
			}
		} else {
			map.remove(planningCluster);
			map.remove(planningMarkers);
		}
	} else if (item.value == '2') {
		if (item.checked) {
			if ($("#cluster").is(':checked')) {
				map.add(bulidingCluster);
			} else {
				map.add(bulidingMarkers);
			}
		} else {
			map.remove(bulidingCluster);
			map.remove(bulidingMarkers);
		}
	} else if (item.value == '3') {
		if (item.checked) {
			if ($("#cluster").is(':checked')) {
				map.add(bulitCluster);
			} else {
				map.add(bulitMarkers);
			}
		} else {
			map.remove(bulitCluster);
			map.remove(bulitMarkers);
		}
	}
}
